/**
 * 
 */
package com.auth.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.auth.config.Config;
import com.auth.model.Account;
import com.auth.model.Role;
import com.service.AbstractService;
import com.util.ConfigUtil;
import com.utils.dbcp.ConnectionManager;
import com.utils.dbcp.ModelGenerator;

public class RoleServiceImpl extends AbstractService implements RoleService 
{
	private Logger logger;
	
	public RoleServiceImpl()
	{
		logger = Logger.getLogger(this.getClass());
		this.dbcp = ConfigUtil.get(Config.SECTION, Config.KEY_DBCP_NAME);
	}
		
	@Override
	public List<Role> getRoles()
	{
		String sql = "select * from role";
		logger.debug("sql: " + sql);
		ModelGenerator<Role> dbcpmg = new ModelGenerator<Role>(Role.class);
		return dbcpmg.generateList(dbcp, sql);
	}

	@Override
	public Role getRole(int id) 
	{
		String sql = "select * from role where id=" + String.valueOf(id);
		logger.debug("sql: " + sql);
		ModelGenerator<Role> dbcpmg = new ModelGenerator<Role>(Role.class);
		return dbcpmg.generate(dbcp, sql);
	}

	@Override
	public boolean saveRole(Account operator, String type, Role role) 
	{
		if (operator == null || operator.getId() == null || operator.getId().length() == 0)
			return false;

		String sql = "";
		if (type.equalsIgnoreCase("insert"))
		{
			role.setId(getTableId("role"));
			sql = 
				"insert into role(id,name,value) " +
				"values(" + role.getId() + ",'" + encodeDb(role.getName()) + "','" + encodeDb(role.getValue()) + "')";
		}
		else if (type.equalsIgnoreCase("update"))
		{
			sql = 
				"update role set name='" + encodeDb(role.getName()) + "',value='" + encodeDb(role.getValue()) + "' " +
				"where id=" + String.valueOf(role.getId());
		}
		else if (type.equalsIgnoreCase("delete"))
		{
			sql = "delete from role where id=" + String.valueOf(role.getId());
		}
		else
		{
			sql = "";
		}
		logger.debug("sql: " + sql);
		if (sql.length() > 0)
		{
			if (ConnectionManager.getInstance().execute(dbcp, sql))
			{
				Role o = null;
				if (!type.equals("delete"))
					o = getRole(role.getId());
				this.logTableOperate("role", type, operator, o);
				return true;
			}
		}
		return false;
	}
}
